<template>
  <el-dialog v-model="visible">
    <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()">
      <el-form-item>
        <el-date-picker style="width: 100%" v-model="pictureDate" value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetimerange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" unlink-panels :shortcuts="shortcuts"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getHisKxincline()">{{ $t("query") }}</el-button>
      </el-form-item>
    </el-form>
    <div id="metalEchart" class="conton"></div>

  </el-dialog>
</template>

<script lang="ts">
import useView from "@/hooks/useView";
import {defineComponent, reactive, toRefs, markRaw} from "vue";
import shortcuts from "@/utils/timeHorizon";
import baseService from "@/service/baseService";
import * as echarts from "echarts";

function getDateThreeDaysBefore(inputDateStr: string) {
  const date = new Date(inputDateStr);
  const threeDaysAgoMillis = date.getTime() - 24 * 60 * 60 * 1000;
  const threeDaysAgoDate = new Date(threeDaysAgoMillis);
  const year = threeDaysAgoDate.getFullYear();
  const month = String(threeDaysAgoDate.getMonth() + 1).padStart(2, '0');
  const day = String(threeDaysAgoDate.getDate()).padStart(2, '0');
  const hours = String(threeDaysAgoDate.getHours()).padStart(2, '0');
  const minutes = String(threeDaysAgoDate.getMinutes()).padStart(2, '0');
  const seconds = String(threeDaysAgoDate.getSeconds()).padStart(2, '0');
  const formattedDate: string = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return formattedDate;
}

export default defineComponent({
  props: {
    stationId: {
      type: String,
    },
    cmdId: {
      type: String,
    }
  },
  setup() {
    const state = reactive({
      visible: false,
      shortcuts,
      pictureDate: [] as any,
      dataForm: {
        cmdId: "",
        type: "",
        startTime: "",
        endTime: "",
        componentId: ""
      } as any,
      dataList: [],
      myChart: null as any,
      unit: "",
      title: ""
    });
    return {...useView(state), ...toRefs(state)};
  },
  watch: {
    pictureDate: {
      handler(val) {
        if (val === null) {
          this.dataForm.startTime = "";
          this.dataForm.endTime = "";
        } else {
          this.dataForm.startTime = val[0];
          this.dataForm.endTime = val[1];
        }
      },
      deep: true
    }
  },
  methods: {
    defaultTime(timeStamp: string) {
      return new Promise((resolve, reject) => {
        this.pictureDate = [getDateThreeDaysBefore(timeStamp), timeStamp];
        resolve("")
      })
    },
    init(type: string, unit: string, title: string, componentId: string, timeStamp: string, cmdId: string) {
      this.visible = true;
      this.$nextTick(() => {
        this.unit = unit;
        this.title = title;
        this.dataForm.cmdId = cmdId;
        this.dataForm.type = type;
        this.dataForm.componentId = componentId;

        let chartDom: any = document.getElementById("metalEchart");
        this.myChart = markRaw(echarts.init(chartDom));

        this.defaultTime(timeStamp).then(() => {
          this.getHisKxincline();
        });

      });
    },
    getHisKxincline() {
      baseService.post(`/KxMetalTempSensor/kxmetaltempsensor/hisMetalTempSensore`, this.dataForm).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }

        let option = {
          tooltip: {
            show: true,
            trigger: 'axis',
            formatter: (params: any) => {
              console.log(params)
              let data = params[0];
              var result = '';
              result += data.seriesName + ':' + data.value + '<br />';
              result += data.axisValueLabel + '<br />';
              return result;
            }
          },
          title: {
            left: 'center',
            text: `${this.title}（${this.unit}）`
          },
          xAxis: {
            data: res.data.uploadTimes
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: this.title,
              type: 'line',
              // smooth: true,
              // symbol: 'none',
              itemStyle: {
                color: 'rgb(45,108,243)'
              },
              data: res.data.hisData
            }
          ]
        };

        console.log(option);

        option && this.myChart.setOption(option);
      });
    }
  }
});
</script>

<style lang="scss" scoped>
.conton {
  width: 100%;
  height: 500px;
}
</style>
